﻿using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructrue.Interfaces;
using BaseData.ReadApi.Application.Command.Roles;
using BaseData.ReadApi.Dto;
using MediatR;

namespace BaseData.ReadApi.Application.CommandHandler.Roles
{
    public class GetRoleItemCommandHandler : IRequestHandler<GetRoleItemCommand, Apiresult<List<ResItemOutput>>>
    {
        private readonly IBasepository<UserInfo> userpository;  // 用户信息仓储接口
        private readonly IBasepository<Role> rolepository;  // 角色仓储接口
        private readonly IBasepository<UserRole> uRpository;  // 用户角色仓储接口
        private readonly IBasepository<Permission> permisspository;  // 权限仓储接口
        private readonly IBasepository<RolePermiss> rolePerpository;  // 角色权限仓储接口
        private readonly IMapper mapper;  // 对象映射器
        private readonly ILogger<GetRoleItemCommandHandler> logger;  // 日志记录器

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="_userpository">用户信息仓储</param>
        /// <param name="_rolepository">角色仓储</param>
        /// <param name="_URpository">用户角色仓储</param>
        /// <param name="_permisspository">权限仓储</param>
        /// <param name="_rolePerpository">角色权限仓储</param>
        /// <param name="_mapper">对象映射器</param>
        /// <param name="_logger">日志记录器</param>
        public GetRoleItemCommandHandler(
            IBasepository<UserInfo> _userpository,
            IBasepository<Role> _rolepository,
            IBasepository<UserRole> _URpository,
            IBasepository<Permission> _permisspository,
            IBasepository<RolePermiss> _rolePerpository,
            IMapper _mapper,
            ILogger<GetRoleItemCommandHandler> _logger)
        {
            userpository = _userpository;
            rolepository = _rolepository;
            uRpository = _URpository;
            permisspository = _permisspository;
            rolePerpository = _rolePerpository;
            mapper = _mapper;
            logger = _logger;
        }
        public async Task<Apiresult<List<ResItemOutput>>> Handle(GetRoleItemCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result= rolepository.GetAll().Select(x => new ResItemOutput { value = x.RoleId, label = x.RoleName }).ToList();
                return new Apiresult<List<ResItemOutput>>()
                {
                    Code = ResultCode.查询成功,
                    Result = result
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                throw;
            }
        }
    }
}
